import requests
from time import sleep, time
import threading
import os

proxies = {
    'http': 'http://127.0.0.1:7890',
    'https': 'http://127.0.0.1:7890',
}


def closeRequest(session):
    sleep(2)
    print("中断")
    session.close()


def download_file(url, savePath):
    # 获取文件所在的目录
    directory = os.path.dirname(savePath)

    # 检查目录是否存在，如果不存在则创建
    if not os.path.exists(directory):
        os.makedirs(directory)
    response = requests.get(url, stream=True, proxies=proxies)
    with open(savePath, 'wb') as file:
        for chunk in response.iter_content(chunk_size=128):
            file.write(chunk)


def getDownloadUrl(url):
    """通过url获得最终的下载地址，"""
    print("开始请求接口", url)
    session = requests.Session()
    t = threading.Thread(target=closeRequest, args=(session,))
    t.start()
    response = session.get(url, proxies=proxies, stream=True, allow_redirects=True, timeout=20)

    if response.status_code == 200:
        print('接口请求成功')
        finalUrl = ""
        # 检查是否有重定向
        if response.history:
            print('接口有重定向')
            print(response.history)

            # 获取重定向后的地址
            # for redirect in response.history:
            #     print('重定向到地址:', redirect.url)

            # 打印最终的URL
            # print('重定向后的最终地址:', response.url)
            finalUrl = response.url
        else:
            print('请求无重定向')
            finalUrl = url

        # # 请求成功
        # result = response.text
        # print("接口返回的数据:", result)
        # return result
        return finalUrl
    else:
        # 请求失败
        print("请求失败，状态码:", response.status_code)
        print("错误信息:", response.text)
        raise ValueError(response.text)


def sendPost(url, data):
    # data = {"key1": "value1", "key2": "value2"}
    response = requests.post(url, data=data, proxies=proxies)
    if response.status_code == 200:
        # 请求成功
        result = response.json()
        print("接口返回的数据:", result)
        return result
    else:
        # 请求失败
        print("请求失败，状态码:", response.status_code)
        print("错误信息:", response.text)
        raise ValueError(response.text)


if __name__ == '__main__':
    # finalUrl = getDownloadUrl(
    #     "https://civitai.com/api/download/models/81507?type=Model&format=SafeTensor")
    finalUrl = getDownloadUrl("https://civitai.com/api/download/models/288982")
    print(finalUrl)
    pass
